package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.heima.common.constans.article.ArticleConstans;
import com.heima.common.constans.message.ArticleForEsConstants;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.mess.ArticleVisitStreamMess;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Value("${fdfs.url}")
    String fileServerUrl;
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //设置分页
        Integer size = dto.getSize();
        if(size ==null || size==0){
            dto.setSize(size);
        }
        //类型参数检验 判断type是否符合要求 12
        if(!loadtype.equals(ArticleConstans.LOADTYPE_LOAD_MORE)&&!loadtype.equals(ArticleConstans.LOADTYPE_LOAD_NEW)){
            loadtype=ArticleConstans.LOADTYPE_LOAD_MORE;
        }
        //文章频道校验 判断频道是否符合要求
         if(StringUtils.isEmpty(dto.getTag())){
             dto.setTag(ArticleConstans.DEFAULT_TAG);
         }
        //时间校验 判断时间是否符合要求
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        if(dto.getMinbehotTime()==null){
            dto.setMinbehotTime(new Date());
        }
        //查询数据
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
        //结果封装
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public Map findArticle(Long id) {
       Map<String, Object> map = new HashMap<>();
        ApArticle apArticle = getById(id);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, id));
        map.put("id",String.valueOf(apArticle.getId()));
        map.put("publishTime",apArticle.getPublishTime());
        map.put("layout",apArticle.getLayout());
        map.put("images",apArticle.getImages());
        map.put("authorId",apArticle.getAuthorId());
        map.put("title",apArticle.getTitle());
        if(apArticleContent!=null){
            map.put("content",apArticleContent.getContent());
        }
        return map;
    }

    /**
     * 重新计算文章分值
     * @param mess
     */
    @Override
    public void updateApArticle(ArticleVisitStreamMess mess) {
        //查询文章
        ApArticle apArticle = getById(mess.getArticleId());
        if(apArticle==null){
            throw  new RuntimeException("当前文章不存在");
        }
        //修改文章
        //阅读数量
        int view =(int)(apArticle.getViews() == null ? mess.getView() : mess.getView() + apArticle.getViews());
        apArticle.setViews(view);
        //点赞数量
        int likes = (int) (apArticle.getLikes() == null ? mess.getLike() : mess.getLike() + apArticle.getLikes());
        apArticle.setLikes(likes);
        //评论数量
        int comment = (int) (apArticle.getComment() == null ? mess.getComment() : mess.getComment() + apArticle.getComment());
        apArticle.setComment(comment);
        //收藏数量
        int collection = (int) (apArticle.getCollection() == null ? mess.getCollect() : mess.getCollect() + apArticle.getCollection());
        apArticle.setCollection(collection);
        //修改数据
        updateById(apArticle);
        //计算文章的分值 当日文章权重*3
        Integer score=computeScore(apArticle);
        score=score*3;
        //查询redis 替换分值较低的数据
        updateAricleCache(apArticle,score, ArticleConstans.HOT_ARTICLE_FIRST_PAGE+apArticle.getChannelId());
        //更新推荐缓存中的数据
        updateAricleCache(apArticle,score,ArticleConstans.HOT_ARTICLE_FIRST_PAGE+ArticleConstans.DEFAULT_TAG);
    }
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    /**
     * 更新文章的分值
     * @param apArticle
     * @param score
     * @param cacheKey
     */
    private void updateAricleCache(ApArticle apArticle, Integer score, String cacheKey) {
        boolean flag=false;
        //获取redis缓存中文章集合
        String articleList = stringRedisTemplate.opsForValue().get(cacheKey);
        if(StringUtils.isNotBlank(articleList)){
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleList, HotArticleVo.class);
            //如果当前缓存中有当前文章，则更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if(hotArticleVo.getId().equals(apArticle.getId())){
                    hotArticleVo.setScore(score);
                    flag=true;
                    break;
                }
            }
            //如果缓存中没有当前文章加入该文章后，重新按score降序 去30条
            if(!flag){
                HotArticleVo hotArticleVo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle,hotArticleVo);
                hotArticleVo.setScore(score);
                hotArticleVoList.add(hotArticleVo);
            }
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());
            //更新数据到缓存中
            stringRedisTemplate.opsForValue().set(cacheKey,JSON.toJSONString(hotArticleVoList));
        }

    }

    /**
     * 计算值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score=0;
        if(apArticle.getLikes()!=null){
            score+=apArticle.getLikes()*ArticleConstans.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews()!=null){
            score+=apArticle.getViews();
        }
        if(apArticle.getComment()!=null){
            score+=apArticle.getComment()*ArticleConstans.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection()!=null){
            score+=apArticle.getCollection()*ArticleConstans.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }

    @Override
    public ResponseResult load2(Short loadtype, ArticleHomeDto dto, boolean firstPage) {
        if(firstPage){
            String jsonStr = stringRedisTemplate.opsForValue().get(ArticleConstans.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                if(!hotArticleVoList.isEmpty() && hotArticleVoList.size()>0){
                    ResponseResult responseResult=null;
                    responseResult.setHost(fileServerUrl);
                  return  ResponseResult.okResult(hotArticleVoList);
                }
            }
        }
        return load(loadtype,dto);
    }
}
